package model.textChat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;

import model.textChat.Interface.MessageObserver;
import model.textChat.Interface.MessageReceive;


public class MessageReceiver implements MessageReceive, SocketObserver
{
	private BufferedReader mReader = null;
	private ArrayList<MessageObserver> observers = new ArrayList<MessageObserver>();
	private boolean conti = true;
	
	
	public void register(MessageObserver observer)
	{
		observers.add( observer );
	}
	
	@Override
	public void run()
	{
	
		while( conti )
		{
			if ( mReader != null )
			{
				Message message = readOneMessage();
				if ( message != null )
				{
					notifyAllObserver( message );
				}
			}
			
			try 
			{
				Thread.sleep( 100 );
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
		

	}
	
	
	private void notifyAllObserver(Message message)
	{
		for (int i = 0; i < observers.size(); i++)
		{
			MessageObserver observer = observers.get( i );
			observer.update( message );
		}
	}
	
	
	private synchronized Message readOneMessage()
	{
		Message message = null;
		try 
		{
			if ( mReader.ready() )
			{
				String sendTime = mReader.readLine();
				if ( sendTime.toCharArray()[0] != 0 )
				{
					
					String senderName = mReader.readLine();
			
					String content = "";
					String contentReaded = mReader.readLine();
					while( !( !contentReaded.isEmpty() && contentReaded.toCharArray()[0] == 3 ) )
					{
						content = content +  contentReaded + "\n";
						contentReaded = mReader.readLine();
					}
			
					
					message = new Message( senderName, sendTime, content );
				}
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return message;
	}
	

	@Override
	public synchronized void update(Socket socket)
	{
		try 
		{
			mReader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
			String response = mReader.readLine();

		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void start() 
	{
		Thread mRcvThread = new Thread( this );
		mRcvThread.start();
	}

	@Override
	public synchronized void end() 
	{
		conti = false;
	}
}
